﻿using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBORpt = Texfina.BORpt.Rh;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace RH
{
   public partial class wfContratoRpt : SearchPage
   {

      public override void SearchData()
      {

         EPerContratoBandeja objE = new EPerContratoBandeja();

         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();

         if (this.txtFechaDesde.Text != "")
            objE.FeInicioA = Convert.ToDateTime(this.txtFechaDesde.Text);
         else
            objE.FeInicioA = null;

         if (this.txtFechaDesde.Text != "")
            objE.FeInicioB = Convert.ToDateTime(this.txtFechaHasta.Text);
         else
            objE.FeInicioB = null;

         if (this.txtidPersonal.Text == "")
            objE.IdPersonal = null;
         else
            objE.IdPersonal = this.hdnidPersonal.Value;

         if (this.ddlidEstable.SelectedItem.Value == "")
            objE.IdEstable = null;
         else
            objE.IdEstable = this.ddlidEstable.SelectedItem.Value;

         if (this.ddlidUniNego.SelectedItem.Value == "")
            objE.IdUNegocio = null;
         else
            objE.IdUNegocio = this.ddlidUniNego.SelectedItem.Value;

         if (this.ddlidCCosto.SelectedItem != null)
            if (this.ddlidCCosto.SelectedItem.Value == "")
               objE.IdCCosto = null;
            else
               objE.IdCCosto = this.ddlidCCosto.SelectedItem.Value;
         else
            objE.IdCCosto = null;

        
         RHBORpt.IPersonal objBO = (RHBORpt.IPersonal)WCFHelper.GetObject<RHBORpt.IPersonal>(typeof(RHBORpt.Personal));
         DataTable dt = objBO.GetByCriteriaImpreContra(objE);

         this.GridSetDataBinding(grdList, dt);

      }


      protected void bttOk_Click(object sender, EventArgs e)
      {
         this.SearchData();
      }

      protected void Page_Load(object sender, EventArgs e)
      {
          try
          {
              if (this.IsPostBack)
              {
                  this.LoadInPostBack();
                  return;
              }
              this.LoadData();
          }
          catch (Exception ex)
          {
              this.hdnMsgOPB.Value = this.CreatePostbackMessage("ERROR", ex.Message, TypeMessageAlert.error, false, "");
          }
      }

      public override void LoadInPostBack()
      {
         this.RegisterGeneralScripts();
      }

      public override void LoadInitialSettings()
      {
         Label lbl = (Label)this.Master.FindControl("lblTitle");
         lbl.Text = "Impresion Masiva de Contratos";
         this.Page.Form.DefaultButton = bttSearch.UniqueID;
      }

      public override void LoadListControls()
      {
         ETablaGenDet objEDet = new ETablaGenDet();
         ECCosto objECCosto = new ECCosto();

         IBOQuery objBOCCosto = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.CCosto));
         MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
         //objECCosto.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         //DataTable dt = objBOCCosto.GetList(objECCosto);
         //WebHelper.LoadListControl(ddlidCCosto, dt, "dsCCosto", "idCCosto", ConstCustomFirstListItem.ITEM_ALL);

         SYBOQry.IEmpresa objBOEmp = (SYBOQry.IEmpresa)WCFHelper.GetObject<SYBOQry.IEmpresa>(typeof(SYBOQry.Empresa));
         EEmpEstable objEEmp = new EEmpEstable();
         objEEmp.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         DataTable dt = objBOEmp.GetEstablecimientos(objEEmp);
         WebHelper.LoadListControl(ddlidEstable, dt, "dsEstable", "idEstable", ConstCustomFirstListItem.ITEM_ALL);

         IBOQuery objBOUNego = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(MGBOQry.UNegocio));
         EUNegocio objEUNeg = new EUNegocio();
         objEUNeg.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         dt = objBOUNego.GetList(objEUNeg);
         WebHelper.LoadListControl(ddlidUniNego, dt, "dsUNegocio", "idUNegocio", ConstCustomFirstListItem.ITEM_ALL);

      }

      public override void DataToControls()
      {

      }
      protected void ddlidUNegocio_SelectedIndexChanged(object sender, EventArgs e)
      {
         ddlidCCosto.Items.Clear();
         EUNegocio objEUNeg = new EUNegocio();
         MGBOQry.IUNegocio objBOUNego = (MGBOQry.IUNegocio)WCFHelper.GetObject<MGBOQry.IUNegocio>(typeof(MGBOQry.UNegocio));
         objEUNeg.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objEUNeg.IdUNegocio = ddlidUniNego.SelectedItem.Value;
         DataTable dt = objBOUNego.GetCCostoXUNegocio(objEUNeg);
         WebHelper.LoadListControl(ddlidCCosto, dt, "dsCCosto", "idCCosto", true, true);
      }
      public override void RegisterGeneralScripts()
      {

         StringBuilder sb = new StringBuilder();

         sb.AppendLine("var varRet = modalDialog('wfPersonal.aspx',725,400);");
         sb.AppendLine("if(varRet==null)");
         sb.AppendLine("return false;");
         sb.AppendLine("ctl = document.getElementById('" + this.hdnidPersonal.ClientID + "');");
         sb.AppendLine("ctl.value = varRet[0];");
         sb.AppendLine("ctl = document.getElementById('" + this.txtidPersonal.ClientID + "');");
         sb.AppendLine("ctl.value = varRet[1];");
         this.txtidPersonal.OnClientClick = sb.ToString();


         sb = new StringBuilder();

         sb.AppendLine("ctl = document.getElementById('" + this.txtidPersonal.ClientID + "');");
         sb.AppendLine("ctl.value = '';");
         sb.AppendLine("ctl = document.getElementById('" + this.ddlidCCosto.ClientID + "');");
         sb.AppendLine("ctl.value = '';");
         this.bttClear.OnClientClick = sb.ToString();

         sb = new StringBuilder();

         sb.AppendLine("function validateEditForm(key){");
         sb.AppendLine("var varRpta = isEmptyControl('" + this.txtFechaDesde.ClientID + "','Seleccione Fecha Desde');");
         sb.AppendLine("if(varRpta==true)");
         sb.AppendLine("return !varRpta;");
         sb.AppendLine("var varRpta = isEmptyControl('" + this.txtFechaHasta.ClientID + "','Seleccione Fecha Hasta');");
         sb.AppendLine("if(varRpta==true)");
         sb.AppendLine("return !varRpta;");
         sb.AppendLine("__doPostBack('" + this.mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");


         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }

      public void RegisterEditPopupScripts()
      {

      }

      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_PRINT:
               PrintReport("");
               break;
            case ConstMenuToolbarValue.BUTTON_EXPORT:
               ExportReport("");
               break;
         }

      }

      public override void PrintReport(string key)
      {
         string strMsg = "";
         DataSet ds = (DataSet)this.GetDataReport(key);
         DataTable dt = new DataTable();
         dt=ds.Tables[0];
         if (dt.Rows.Count > 0)
         {
            MemoryStream[] msArray = new MemoryStream[dt.Rows.Count];

            DataTable dtClone = new DataTable();
            dtClone = dt.Clone();

            string strIdTipoTrab = "";
            string strStProrroga = "";
            string strStRemuMinima = "";
         
            int x = 0;

            foreach (DataRow dr in dt.Rows)
            {
               dtClone.ImportRow(dr);

               strIdTipoTrab = dr["idTipoTrab"].ToString();
               strStProrroga = dr["stProrroga"].ToString();
               strStRemuMinima = dr["stRemuMinima"].ToString();
              

               ReportDocument objRpt = new ReportDocument();

               switch (strIdTipoTrab)
               {

                  case ConstTipoTrabajador.EMPLEADO:

                     if (strStProrroga == ConstFlagEstado.DESACTIVADO)
                     {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/Contratos.rpt"));
                     }

                     else
                     {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/Contratos2.rpt"));
                     }

                     break;


                  case ConstTipoTrabajador.OBRERO:

                     if (strStProrroga == ConstFlagEstado.DESACTIVADO)
                     {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero.rpt"));
                        break;
                     }

                     if (strStProrroga == ConstFlagEstado.ACTIVADO && strStRemuMinima == ConstFlagEstado.ACTIVADO)
                     {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero2.rpt"));
                        break;
                     }
                     if (strStProrroga == ConstFlagEstado.ACTIVADO && strStRemuMinima == ConstFlagEstado.DESACTIVADO)
                     {
                        objRpt.Load(this.MapPath(ConstSistema.ROOT_FOLDER_PATH + "/ContratoObrero3.rpt"));
                        break;
                     }

                     break;

                  default:
                     strMsg = "No tiene Registros";
                     this.hdnMsgOPB.Value = this.CreatePostbackMessage("ATENCIÓN", "No se encotraron Resultados", TypeMessageAlert.atention, false, "");
                     break;
               }

               objRpt.SetDataSource(dtClone);

               MemoryStream ms = new MemoryStream();

               Response.Clear();

               ms = (MemoryStream)objRpt.ExportToStream(ExportFormatType.PortableDocFormat);
               msArray[x] = ms;
               objRpt.Dispose();
               objRpt = null;
               dtClone.Clear();
               x++;
            }

            MemoryStream msRes = ExcelHelper.MergePDFFiles(msArray);

            Response.AddHeader("Content-Disposition", "attachment;filename=CONTRATOS.pdf");

            Response.Buffer = true;
            Response.ContentType = "application/pdf";
            Response.OutputStream.Write(msRes.GetBuffer(), 0, msRes.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            msRes.Close();
            Response.Flush();
            Response.End();
         }
         else {

            strMsg = "No Existen Registros";
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("ATENCIÓN", strMsg, TypeMessageAlert.atention, false, "");
         }
        
     
      }
      
      public override void ExportReport(string key)
      {
         DataSet ds = (DataSet)this.GetDataReport(key);
         if (ds.Tables[0].Rows.Count == 0)
         {
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("ATENCIÓN", "No se encotraron Resultados", TypeMessageAlert.atention, false, "");
            return;
         }
         ExcelHelper.ToExcel(ds, "Data.xls", Response);

      }

      public override object GetDataReport(string key)
      {

         EPerContratoBandeja objE = new EPerContratoBandeja();
         RHBORpt.IPersonal objBO = (RHBORpt.IPersonal)WCFHelper.GetObject<RHBORpt.IPersonal>(typeof(RHBORpt.Personal));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();

         objE.FeInicioA =Convert.ToDateTime(this.txtFechaDesde.Text);

         objE.FeInicioB = Convert.ToDateTime(txtFechaHasta.Text);

         if (this.txtidPersonal.Text == "")
            objE.IdPersonal = null;
         else
            objE.IdPersonal = this.hdnidPersonal.Value;

         if (this.ddlidEstable.SelectedItem.Value == "")
            objE.IdEstable = null;
         else
            objE.IdEstable = this.ddlidEstable.SelectedItem.Value;

         if (this.ddlidUniNego.SelectedItem.Value == "")
            objE.IdUNegocio = null;
         else
            objE.IdUNegocio = this.ddlidUniNego.SelectedItem.Value;

         if (this.ddlidCCosto.SelectedItem != null)
            if (this.ddlidCCosto.SelectedItem.Value == "")
               objE.IdCCosto = null;
            else
               objE.IdCCosto = this.ddlidCCosto.SelectedItem.Value;
         else
            objE.IdCCosto = null;

         DataTable dt = objBO.GetContratosMasivamente(objE);

         DataSet ds = new DataSet();
         ds.Tables.Add(dt);
   

         return ds;


      }

   }
}